import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  mockCsvData: string;
  
  mockHeaders = `Name,Type,Value
  `
  originalData = [
    {name: 'nameA123',type: 'typeA', value: 80},
    {name: 'nameB',type: 'typeB', value: 30},
    {name: 'nameC',type: 'nameC', value: 20},
  ]

  convertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','
            line += array[i][index];
        }
        str += line + '\r\n';
    }
    return str;
}

  formatToCsvData() {
    let itemsFormatted = [];
    this.originalData.forEach((item) => {
      itemsFormatted.push({
          name: item.name.replace(/,/g, ''), // remove commas
          type: item.type,
          value: item.value,
      });
    });
    const jsonObject = JSON.stringify(itemsFormatted);
    const csv = this.convertToCSV(jsonObject);
    this.mockCsvData =  this.mockHeaders + csv;
  }

  fileTitle = 'export-result';

  download() {
    this.formatToCsvData()
    const exportedFilenmae = this.fileTitle + '.csv';

    const blob = new Blob([this.mockCsvData], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) {
      // IE 10+
      navigator.msSaveBlob(blob, exportedFilenmae);
    } else {
      const link = document.createElement('a');
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', exportedFilenmae);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }
  }
}
